import React from 'react';
import { Spin } from 'antd';

class Loading extends React.PureComponent {
  state = {
    loading: false,
  };

  start() {
    this.setState({
      loading: true,
    });
  }

  stop() {
    this.setState({
      loading: false,
    });
  }

  render() {
    const { loading } = this.state;
    return <Spin spinning={loading}>{this.props.children}</Spin>;
  }
}
const loadingRef = React.createRef();
export default function SavePlugin(options = {}) {
  const { save } = options;
  return {
    commands: {
      save: editor => {
        const { value } = editor;
        const data = value.toJS();
        const startLoading = () => {
          if (loadingRef.current) {
            loadingRef.current.start();
          }
        };
        const stopLoading = () => {
          if (loadingRef.current) {
            loadingRef.current.stop();
          }
        };
        startLoading();
        save({ ...data })
          .then(stopLoading)
          .catch(stopLoading);
      },
    },
    renderEditor: (props, editor, next) => {
      const children = next();
      return <Loading ref={loadingRef}>{children}</Loading>;
    },
  };
}
